package seismosurfer.servlets;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seismosurfer.data.CountryData;
import seismosurfer.data.UserData;
import seismosurfer.domain.User;
import seismosurfer.util.Registry;
import seismosurfer.util.Util;

import com.bbn.openmap.util.Debug;

/**
 * This servlet handles user registration.
 *
 */
public class RegistrationController extends BaseServlet {
    
    private static final long serialVersionUID = -6182955496759698691L;

    public static final String REGISTRATION = "registration";

    public static final String REGISTERED = "registered";

    // Initialize global variables
    public void init() throws ServletException {
    }

    // Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if (Util.isNull(request.getParameter(USERNAME))) {
            Debug
                    .output("We have a new user. Forward her to registration page...");

            // load the countries first and transform them to an html list
            setCountries(request, "GR");

            forward("/registration.jsp", request, response);
        } else {
            // process the form

            UserData ud = new UserData();

            ud.setUserName(request.getParameter(USERNAME));

            // validate passwords here (maybe this code belongs to User class)
            String[] passwords = request.getParameterValues(PASSWORD);
            if (passwords.length != 2) {
                ud.setPassword(null);
            } else if (!passwords[0].equals(passwords[1])) {
                ud.getNotification().put(PASSWORD, User.WRONG_SPELLING);
            }

            ud.setPassword(request.getParameter(PASSWORD));
            ud.setNickName(request.getParameter(NICKNAME));
            ud.setCountry(request.getParameter(COUNTRY));
            ud.setFirstName(request.getParameter(FIRSTNAME));
            ud.setLastName(request.getParameter(LASTNAME));
            ud.setCity(request.getParameter(CITY));

            User user = new User(ud);
            boolean registered = user.registerUser();

            if (registered) {
                Debug.output("New user was registered successfully...");

                request.removeAttribute(ERROR);

                Debug.output(ud.toString());
                request.setAttribute(REGISTRATION, ud);
                forward("/registered.jsp", request, response);
            } else {

                // There were errors during registration...
                // They are included in users` data...

                setErrors(ud.getNotification(), request);

                // Store the submitted data in request scope
                request.setAttribute(REGISTRATION, ud);

                setCountries(request, ud.getCountry());

                Debug
                        .output("Forwarding to registration.jsp because of errors...");

                forward("/registration.jsp", request, response);
            }

        }

    }

    private void setCountries(HttpServletRequest request, String selected) {

        // load the countries first and transform them to an html list
        String countries = getCountries(Registry.getCountries(), selected);

        request.setAttribute(Registry.COUNTRIES, countries);
    }
    
    /**
     * Converts a list of countries data into 
     * an HTML combo box.
     * 
     * @param countries the List of countries` data
     * @param selectedCode the code of the country that
     *        will be selected
     * @return a String that contains an HTML combo box
     */
    protected String getCountries(List countries, String selectedCode) {
        StringBuffer html = new StringBuffer(200);
        String beginTag = "<option value=\"";
        String endTag = "</option>";
        String selected = "<option selected value=\"";

        for (Iterator iter = countries.iterator(); iter.hasNext();) {
            CountryData item = (CountryData) iter.next();
            String code = item.getCode().trim();
            String country = item.getName().trim();

            if (code.equalsIgnoreCase("NK")) {
                continue;
            } else if (code.equalsIgnoreCase(selectedCode)) {
                html.append(selected);
            } else {
                html.append(beginTag);
            }
            html.append(code + "\">" + country + endTag);
        }
        return html.toString();
    }

    public void destroy() {
    }
}